package com.hlhj.carview.customView

import android.animation.Animator
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.content.res.TypedArray
import android.graphics.*
import android.media.MediaPlayer
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.example.mymvp.log

import com.hlhj.carview.R

/**
 * Created by Never Fear   on 2018\12\20 0020.
 * Never More....
 */

class SlideLockView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {

    private var mLockBitmap: Bitmap? = null
    private val mLockDrawableId: Int
    private var mPaint: Paint? = null
    private val mLockRadius: Int
    private var mTipText = ""
    private val mTipsTextSize: Int
    private val mTipsTextColor: Int
    private val mTipsTextRect = Rect()

    private var mLocationX: Float = 0.toFloat()
    private var mIsDragable = false
    private var mLockListener: OnLockListener? = null

    private var pointBitmap:Bitmap?=null
    private var pointPro=1
    private var pointAnimator:Animator?=null
    private val poinitHandler=object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            pointPro++
            if (pointPro>4){
                pointPro=1
            }

            invalidate()
            this.sendEmptyMessageDelayed(1,200)
        }
    }
    private var mediaPlayer:MediaPlayer?=null

    init {

        val tp = context.obtainStyledAttributes(attrs, R.styleable.SlideLockView, defStyleAttr, 0)
        mLockDrawableId = tp.getResourceId(R.styleable.SlideLockView_lock_drawable, -1)
        mLockRadius = tp.getDimensionPixelOffset(R.styleable.SlideLockView_lock_radius, 1)
        mTipText = tp.getString(R.styleable.SlideLockView_lock_tips_tx)
        mTipsTextSize = tp.getDimensionPixelOffset(R.styleable.SlideLockView_locl_tips_tx_size, 12)
        mTipsTextColor = tp.getColor(R.styleable.SlideLockView_lock_tips_tx_color, Color.BLACK)

        tp.recycle()

        if (mLockDrawableId == -1) {
            throw RuntimeException("未设置滑动解锁图片")
        }

        mediaPlayer= MediaPlayer.create(context,R.raw.music)
        init(context)

    }

    private fun init(context: Context) {
        mPaint = Paint()
        mPaint!!.isAntiAlias = true
        mPaint!!.textSize = mTipsTextSize.toFloat()
        mPaint!!.color = Color.WHITE

        mLockBitmap = BitmapFactory.decodeResource(context.resources, mLockDrawableId)
        val oldSize = mLockBitmap!!.height
        val newSize = mLockRadius * 2
        val scale = newSize * 1.0f / oldSize
        val matrix = Matrix()
        matrix.setScale(scale, scale)
        mLockBitmap = Bitmap.createBitmap(mLockBitmap!!, 0, 0, oldSize, oldSize, matrix, true)

        pointBitmap=BitmapFactory.decodeResource(context.resources,R.drawable.ic_zsf)
        pointAnimator=ObjectAnimator.ofInt(1,4)
        pointAnimator?.interpolator=null
        pointAnimator?.duration=4000

       /* val oldSize2 = pointBitmap!!.height
        val newSize2 = mLockRadius * 2
        val scale2 = newSize2 * 1.0f / oldSize2
        val matrix2 = Matrix()
        matrix2.setScale(scale2, scale2)
        pointBitmap = Bitmap.createBitmap(pointBitmap!!, 0, 0, oldSize2, oldSize2, matrix2, true)*/
    }
    //开启指向循环
    open fun startLoop(){
        poinitHandler?.sendEmptyMessage(1)
    }
    override fun onDraw(canvas: Canvas) {

        canvas.getClipBounds(mTipsTextRect)
        val cHeight = mTipsTextRect.height()
        val cWidth = mTipsTextRect.width()
        mPaint!!.textAlign = Paint.Align.LEFT
        mPaint!!.getTextBounds(mTipText, 0, mTipText.length, mTipsTextRect)
        val x = cWidth / 2f - mTipsTextRect.width() / 2f - mTipsTextRect.left.toFloat()
        val y = cHeight / 2f + mTipsTextRect.height() / 2f - mTipsTextRect.bottom
        canvas.drawText(mTipText, x, y, mPaint!!)


        //画指向
        doPoint(canvas)
        //画车车
        mPaint?.alpha=255
        val rightMax = width - mLockRadius * 2
        if (mLocationX < 0) {
            val rect = Rect(0, 0, mLocationX.toInt(), height)

/*            canvas.clipRect(rect)
            canvas.drawColor(Color.WHITE)*/

            canvas.drawBitmap(mLockBitmap!!, 0f, 0f, mPaint)


        } else if (mLocationX > rightMax) {

            val rect = Rect(0, 0, mLocationX.toInt(), height)
/*            canvas.clipRect(rect)
            canvas.drawColor(Color.WHITE)*/

            canvas.drawBitmap(mLockBitmap!!, rightMax.toFloat(), 0f, mPaint)

        } else {
   /*         val rect = RectF(0f, 0f, mLocationX+mLockBitmap!!.width, height.toFloat())
            canvas.drawRoundRect(rect,mLockRadius.toFloat(),mLockRadius.toFloat(),mPaint)*/
            canvas.drawBitmap(mLockBitmap!!, mLocationX, 0f, mPaint)

        }

    }
    private fun doPoint(canvas: Canvas) {
        when(pointPro){
            4->{
                mPaint?.alpha = 255
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 18) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 204
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 27) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 153
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 36) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 100
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 45) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)
            }
            3->{
                mPaint?.alpha = 100
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 18) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 255
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 27) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 204
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 36) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 153
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 45) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)
            }
            2->{
                mPaint?.alpha = 153
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 18) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 100
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 27) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 255
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 36) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 204
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 45) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)
            }
            1->{
                mPaint?.alpha = 204
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 18) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 153
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 27) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)
                mPaint?.alpha = 100
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 36) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

                mPaint?.alpha = 255
                canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 45) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)
            }
        }
        mPaint?.alpha = 102
        if (pointPro == 4) mPaint?.alpha = 255
        canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 18) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

        mPaint?.alpha = 77
        if (pointPro == 3) mPaint?.alpha = 255
        canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 27) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

        mPaint?.alpha = 51
        if (pointPro == 2) mPaint?.alpha = 255
        canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 36) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)

        mPaint?.alpha = 26
        if (pointPro == 1) mPaint?.alpha = 255
        canvas?.drawBitmap(pointBitmap!!, width.toFloat() * (100 - 45) / 100, (height.toFloat() / 2) - pointBitmap?.height?.toFloat()!! / 2, mPaint)
    }

    private var lastX:Float=0f
    var isAuto=false
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                val xPos = event.x
                val yPos = event.y
                if (isTouchLock(xPos, yPos)) {
                    mLocationX = xPos - mLockRadius
                    mIsDragable = true
                    invalidate()
                } else {
                    mIsDragable = false
                }
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                if (!mIsDragable) return true
                val rightMax = width - mLockRadius * 2
                resetLocationX(event.x, rightMax.toFloat())
                log("fhp","拖拽差距为${event.x-lastX}")
                if ((event.x-lastX)>10){
                    log("fhp","设置了吗？")
                    //自己划过去
                    isAuto=true
                }else{
                    isAuto=false
                }
                invalidate()

                lastX=event.x
                if (mLocationX >= rightMax) {
                    mIsDragable = false
                    mLocationX = 0f
                    invalidate()
                    if (mLockListener != null) {
                        playMusic()

                        mLockListener!!.onOpenLockSuccess()
                    }
                    Log.e("AnimaterListener", "解锁成功")
                }

                return true
            }
            MotionEvent.ACTION_UP -> {
                if (!mIsDragable) return true
                log("fhp","抬起的时候${isAuto}")
                if (isAuto){
                    goTolockSelf(lastX)
                }else{
                    resetLock()
                }
                isAuto=false
                lastX=0f
            }
        }
        return super.onTouchEvent(event)
    }
    private fun playMusic(){
        val player = MediaPlayer.create(context, R.raw.music)
        player?.start()
    }
    private fun goTolockSelf(x:Float){
        val animator = ObjectAnimator.ofFloat(x, (width).toFloat())
        animator.duration=300
        animator?.addUpdateListener {
            value->
            val animatedValue = value.animatedValue as Float
            resetLocationX(animatedValue,(width-mLockRadius*2).toFloat())
            if (animatedValue==width.toFloat()){
                mIsDragable = false
                mLocationX = 0f
                invalidate()
                isAuto=false
                if (mLockListener != null) {
                    playMusic()
                    mLockListener!!.onOpenLockSuccess()
                }
                Log.e("AnimaterListener", "解锁成功")
            }

            invalidate()
        }
        animator?.start()
    }
    private fun resetLock() {
        playMusic()
        val anim = ValueAnimator.ofFloat(mLocationX, 0f)
        anim.duration = 300
        anim.addUpdateListener { valueAnimator ->
            mLocationX = valueAnimator.animatedValue as Float
            invalidate()
        }
        isAuto=false
        anim.start()
    }

    private fun resetLocationX(eventXPos: Float, rightMax: Float) {

        mLocationX = eventXPos - mLockRadius
        if (mLocationX < 0) {
            mLocationX = 0f
        } else if (mLocationX >= rightMax) {
            mLocationX = rightMax
        }
    }

    private fun isTouchLock(xPos: Float, yPox: Float): Boolean {
        val centerX = mLocationX + mLockRadius
        val diffX = xPos - centerX
        val diffY = yPox - mLockRadius

        return diffX * diffX + diffY * diffY < mLockRadius * mLockRadius
    }


    fun setmLockListener(mLockListener: OnLockListener) {
        this.mLockListener = mLockListener
    }

    interface OnLockListener {
        fun onOpenLockSuccess()
    }
}